package ua.edu.nuos.jeetraining2012.cms.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ua.edu.nuos.jeetraining2012.cms.service.Material;
import ua.edu.nuos.jeetraining2012.cms.util.interceptor.ShiroSecurity;
import ua.edu.nuos.jeetraining2012.cms.util.servlet.CmsServlet;
import ua.edu.nuos.jeetraining2012.cms.util.template.TemplateRenderer;
import ua.edu.nuos.jeetraining2012.cms.util.template.material.IndexTemplate;
import ua.edu.nuos.jeetraining2012.cms.util.template.material.ViewTemplate;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Course controller servlet.
 * <p/>
 * Available actions:
 * <ul>
 *     <li>index &mdash; list of all available courses.</li>
 *     <li>view &mdash; show detailed info about selected course.</li>
 * </ul>
 *
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 23.04.13 Time: 22:21
 * @since 1.0
 */
@ShiroSecurity
@WebServlet(urlPatterns = {"/material", "/material/*"})
public class MaterialServlet extends CmsServlet {

    /**
     * Define current controller name.
     */
    final private static String CURRENT_CONTROLLER = "material";

    /**
     * Define logger.
     */
    final static private Logger logger = LoggerFactory.getLogger(MaterialServlet.class);

    @EJB
    private Material material;

    // Constructors.
    public MaterialServlet() {
        logger.debug("MaterialServlet - invocation.");
    }

    /**
     * Index action.
     * <p/>
     * Show all available courses.
     *
     * @param request           HttpServletRequest
     * @param response          HttpServletResponse
     */
    public void indexAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.debug("indexAction() - started.");
        final String ACTION_NAME = "index";

        String courseIdRequest = request.getParameter("course_id");
        Long courseId = null;
        logger.debug("course id: {}", courseIdRequest);

        if (courseIdRequest == null) {
            logger.debug("course id is {}, redirecting to course list.", courseIdRequest);
            try {
                response.sendRedirect(request.getContextPath() + "/course");
                return;
            } catch (IOException e) {
                logger.error("indexAction() - can't forward to /course");
            }
        } else {
            courseId = Long.valueOf(courseIdRequest);
            logger.debug("courseId long {}", courseId);
        }

        TemplateRenderer renderer = new TemplateRenderer();
        IndexTemplate template = new IndexTemplate(courseId);
        template.setCurrentController(CURRENT_CONTROLLER);
        template.setCurrentAction(ACTION_NAME);

        template.setContextPath(request.getContextPath());

        if (!renderer.process(template, response.getWriter())) {
            try {
                request.getRequestDispatcher("/error.jspx").forward(request, response);
            } catch (ServletException e) {
                logger.error("indexAction() - Can't forward to error.jspx", e);
            }
        }

        logger.debug("indexAction() - finished.");
    }

    /**
     * View action.
     * <p/>
     * Show course details.
     *
     * @param request           HttpServletRequest user request.
     * @param response          HttpServletResponse server response.
     * @throws java.io.IOException      Will thrown if can't get writer or this exception produced by
     *                          {@link javax.servlet.http.HttpServletRequest#getRequestDispatcher(String)} method.
     */
    public void viewAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.debug("viewAction() - started.");

        final String ACTION_NAME = "view";
        String materialIdRequest = request.getParameter("material_id");
        String currentCollapseNumRequest = request.getParameter("si");
        Long materialId = null;
        Integer currentCollapseNum = (currentCollapseNumRequest == null)
                ? 0
                : Integer.valueOf(currentCollapseNumRequest);

        if (materialIdRequest == null) {
            logger.debug("material id is {}. Redirecting to course list.", materialId);
            try {
                response.sendRedirect(request.getContextPath() + "/course");
                return;
            } catch (IOException e) {
                logger.error("indexAction() - can't forward to /course");
            }
        } else {
            materialId = Long.valueOf(materialIdRequest);
            logger.debug("long material id is {}", materialId);
        }

        TemplateRenderer renderer = new TemplateRenderer();
        ViewTemplate template = new ViewTemplate(materialId);
        template.setCurrentController(CURRENT_CONTROLLER);
        template.setCurrentAction(ACTION_NAME);
        template.setCurrentCollapseNum(currentCollapseNum);

        template.setContextPath(request.getContextPath());


        if (!renderer.process(template, response.getWriter())) {
            try {
                request.getRequestDispatcher("/error.jspx").forward(request, response);
            } catch (ServletException e) {
                logger.error("indexAction() - Can't forward to error.jspx", e);
            }
        }

        logger.debug("viewAction() - finished.");
    }

}
